<?php
/**
* @file boardnewsmult.php
* Systemblock multiple boardnews
*
* @author PortaMx - Portal Management Extension
* @author Copyright 2008-2011 by PortaMx - http://portamx.com
* @Version: 1.0 RC4
* @Date: 23.02.2011
*/

if(!defined('PortaMx'))
	die('This file can\'t be run without PortaMx');

/**
* @class pmxc_boardnewsmult
* Systemblock multiple boardnews
* @see boardnewsmult.php
* @author Copyright by PortaMx - http://portamx.com
*/
class pmxc_boardnewsmult extends PortaMxC_SystemBlock
{
	var $posts;				///< all posts
	var $attaches;		///< all ataches

	/**
	* InitContent.
	* Checks the cache status and create the content.
	*/
	function pmxc_InitContent()
	{
		global $context, $scripturl, $pmxCacheFunc;

		// if visible init the content
		if($this->visible)
		{
			if($this->cfg['cache'] > 0)
			{
				// check the block cache
				if(($cachedata = $pmxCacheFunc['get']($this->cache_key, $this->cache_mode)) !== null)
					list($dummy, $dummy, $this->posts, $this->attaches) = $cachedata;
				else
				{
					$this->fetch_data();
					$cachedata = array(array(), array(), $this->posts, $this->attaches);
					$pmxCacheFunc['put']($this->cache_key, $cachedata, $this->cache_time, $this->cache_mode);
				}
				unset($cachedata);
			}
			else
				$this->fetch_data();

			// paging...
			if(!empty($this->cfg['config']['settings']['onpage']) && count($this->posts) > $this->cfg['config']['settings']['onpage'])
				$this->pmxc_constructPageIndex(count($this->posts), $this->cfg['config']['settings']['onpage']);
		}
		// return the visibility flag (true/false)
		return $this->visible;
	}

	/**
	* fetch_data.
	* Fetch Boards, Topics, Messages and Attaches.
	*/
	function fetch_data()
	{
		global $context, $smcFunc, $user_info, $modSettings, $settings, $scripturl, $txt;

		$boards = !empty($this->cfg['config']['settings']['board']) ? $this->cfg['config']['settings']['board'] : array();
		$this->posts = null;
		$this->attaches = null;

		if(!empty($boards))
		{
			// Load the message icons
			$stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled', 'wireless');
			$icon_sources = array();
			foreach ($stable_icons as $icon)
				$icon_sources[$icon] = 'images_url';

			// fetch the first post from each baord
			$request = $smcFunc['db_query']('', '
					SELECT b.name, t.id_topic, t.locked, t.num_replies, t.num_views, m.*
					FROM {db_prefix}boards AS b
					LEFT JOIN {db_prefix}topics AS t ON (b.id_board = t.id_board AND t.id_last_msg = b.id_last_msg)
					LEFT JOIN {db_prefix}messages AS m ON (t.id_first_msg = m.id_msg)
					WHERE b.id_board IN ({array_int:boards}) AND {query_wanna_see_board}'.
					($modSettings['postmod_active'] ? ' AND m.approved = {int:is_approved}' : ''). '
					ORDER BY t.id_board asc',
				array(
					'boards' => $boards,
					'is_approved' => 1
				)
			);

			while ($row = $smcFunc['db_fetch_assoc']($request))
			{
				if(!is_null($row['id_topic']))		// empty board?
				{
					$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);

					// Check that this message icon is there...
					if (empty($modSettings['messageIconChecks_disable']) && !isset($icon_sources[$row['icon']]))
						$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.gif') ? 'images_url' : 'default_images_url';

					censorText($row['subject']);
					censorText($row['body']);

					$this->posts[] = array(
						'id_board' => $row['id_board'],
						'board_name' => $row['name'],
						'id' => $row['id_topic'],
						'message_id' => $row['id_msg'],
						'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.gif" align="middle" alt="' . $row['icon'] . '" border="0" />',
						'subject' => $row['subject'],
						'time' => timeformat($row['poster_time']),
						'timestamp' => forum_time(true, $row['poster_time']),
						'body' => $row['body'],
						'replies' => $row['num_replies'],
						'views' => $row['num_views'],
						'poster' => array(
							'id' => $row['id_member'],
							'name' => $row['poster_name'],
							'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
							'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
						),
						'locked' => !empty($row['locked']),
					);
				}
			}
			$smcFunc['db_free_result']($request);

			if(!is_null($this->posts))
			{
				// get attachments if show thumnails set
				if(AllowedTo('view_attachments', $this->cfg['config']['settings']['board']))
				{
					if(!empty($this->cfg['config']['settings']['thumbs']))
					{
						$msgids = null;
						foreach($this->posts as $post)
							$msgids[] = $post['message_id'];

						$request = $smcFunc['db_query']('', '
							SELECT a.id_attach, a.id_thumb, a.filename, a.id_msg, m.id_topic
								FROM {db_prefix}attachments a
								LEFT JOIN {db_prefix}messages m ON (a.id_msg = m.id_msg)
							WHERE m.id_msg IN ({array_int:msgids})
								AND a.approved = 1
								AND a.mime_type LIKE {string:like}
							ORDER BY a.id_attach',
							array(
								'msgids' => $msgids,
								'like' => 'IMAGE%'
							)
						);

						$thumbs = array();
						while($row = $smcFunc['db_fetch_assoc']($request))
						{
							if(!in_array($row['id_attach'], $thumbs))
							{
								$thumbs[] = $row['id_thumb'];
								$this->attaches[$row['id_msg']][] = array(
									'topic' => $row['id_topic'],
									'image' => $row['id_attach'],
									'thumb' => empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'],
									'fname' => str_replace('_thumb', '', $row['filename'])
								);
							}
						}
						$smcFunc['db_free_result']($request);
					}
				}
			}
		}
	}

	/**
	* ShowContent.
	* Output the content and add necessary javascript
	*/
	function pmxc_ShowContent()
	{
		global $context, $settings, $modSettings, $scripturl, $txt;

		if(!is_null($this->posts))
		{
			$L_R = empty($context['right_to_left']) ? 'left' : 'right';
			$R_L = empty($context['right_to_left']) ? 'right' : 'left';

			// put the rescale code to the content
			if(!empty($this->cfg['config']['settings']['rescale']))
			{
				$jsImg = 0;
				echo '
				<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
					var MsgImages'.$this->cfg['id'].' = new Array()';

				foreach($this->posts as $pid => $value)
				{
					if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
						$this->posts[$pid]['hsbody'] = $this->posts[$pid]['body'];

					if(preg_match_all('~<img[^>]*>~iS', $this->posts[$pid]['body'], $matches) > 0)
					{
						foreach($matches[0] as $data)
						{
							preg_match('~src?=?"([^\"]*\")~i', $data, $src);
							if(isset($src[1]) && strpos($src[1], $modSettings['smileys_url']) === false)
							{
								if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
								{
									$tmp = str_replace($src[0], ' name="pmx'. $this->cfg['id'] .'img'. $jsImg .'" title="'. substr(strrchr($src[1], '/'), 1) .' '. $src[0], $data);
									$this->posts[$pid]['hsbody'] = substr_replace($this->posts[$pid]['hsbody'],
										'<a href="'. $src[1].' class="highslide" title="'. $txt['pmx_hs_expand'] .'" onclick="return hs.expand(this, {align: \'center\', captionEval: \'this.thumb.title\'})">' .$tmp .'</a>',
										strpos($this->posts[$pid]['hsbody'], $data), strlen($data));
								}
								$tmp = str_replace($src[0], ' name="pmx'. $this->cfg['id'] .'img'. $jsImg .'" '. $src[0], $data);
								$this->posts[$pid]['body'] = substr_replace($this->posts[$pid]['body'], $tmp, strpos($this->posts[$pid]['body'], $data), strlen($data));

								echo '
					MsgImages'.$this->cfg['id'].'['. $jsImg .'] = "pmx'. $this->cfg['id'] .'img'. $jsImg .'";';
								$jsImg++;
							}
						}
					}
				}
				echo '
					// ]]></script>';
			}

			$is_Split = $this->cfg['config']['settings']['split'];
			$is_last = (!empty($this->pageindex) ? ($this->startpage + $this->postspage > count($this->posts) ? count($this->posts) - $this->startpage : $this->postspage) : count($this->posts));

			if($is_Split)
				$half = ceil($is_last / 2);
			else
				$half = $is_last;

			// put the data to the content
			if(!empty($this->cfg['customclass']))
				$isCustFrame = !empty($this->cfg['customclass']['postframe']);
			else
				$isCustFrame = false;
			$spanclass = $isCustFrame && !empty($this->cfg['config']['visuals']['postbody']) ? $this->cfg['config']['visuals']['postbody'] .' ' : '';

			if(!empty($this->pageindex))
				echo '
				<a name="top'. $this->cfg['uniID'] .'"></a>';

			if(!empty($this->pageindex) && !empty($this->cfg['config']['settings']['pgidxtop']))
				echo '
				<div class="smalltext pmx_pgidx_top">'. $txt['pages']. ': '. $this->pageindex . (!empty($modSettings['topbottomEnable']) ? $context['menu_separator'] . ' &nbsp;&nbsp;<a href="#bot'. $this->cfg['uniID'] .'"><strong>' . $txt['go_down'] . '</strong></a>' : '') .'</div>';

			echo '
				<table width="100%" cellpadding="0" cellspacing="0" border="0" style="table-layout:fixed;">
					<tr>
						<td'.($is_Split ? ' style="padding-'.$R_L.':'. ceil($context['pmx']['settings']['panelpad'] / 2) .'px; width:50%;"' : '').' valign="top">';

			reset($this->posts);
			for($i = 0; $i < $this->startpage; $i++)
				each($this->posts);

			while(!empty($is_last))
			{
				list($pid, $post) = each($this->posts);
				if($is_Split && empty($half))
				{
					echo '
						</td>
						<td style="padding-'.$L_R.':'. ceil($context['pmx']['settings']['panelpad'] / 2).'px; width:50%;" valign="top">';

					reset($this->posts);
					for($i = -1; $i < $this->startpage; $i++)
						each($this->posts);
					list($pid, $post) = each($this->posts);
				}
				$half--;
				$is_last--;

				if(empty($half) && !empty($this->pageindex))
					echo '
							<a name="bot'. $this->cfg['uniID'] .'"></a>';

				echo '
							<div class="'. str_replace('bg', '_bar', $this->cfg['config']['visuals']['postheader']) .' catbg_grid">
								<h4 id="pmx'.$this->cfg['id'].'bnmpos'. $post['message_id'] .'" class="'. $this->cfg['config']['visuals']['postheader'] .' catbg_grid">
									'. $post['icon'] .'<span class="normaltext cat_msg_title"><a href="' . $scripturl . '?topic=' . $post['id'] . '.0">'. $post['subject'] .'</a></span>
								</h4>
							</div>
							<div'.(empty($half) || empty($is_last) ? '' :' style="margin-bottom:'. $context['pmx']['settings']['panelpad'] .'px;"') .'>';

				$postbody = trim($this->cfg['config']['visuals']['postbody'] .' '. $this->cfg['config']['visuals']['postframe']);
				if(!empty($postbody))
					echo '
							<div class="'. $postbody .'" style="padding:0 5px;">';

				if(!empty($this->cfg['config']['settings']['equal']) && !empty($this->cfg['config']['settings']['split']))
					echo '
							<div class="pmx_equalheight_'. $this->cfg['id'] .'">';

				echo '
							<div class="smalltext" style="float:'.$L_R.';">
								'. $txt['pmx_text_postby'] . $post['poster']['link'] .', '. $post['time'] .'
							</div>
							<div class="smalltext" style="float:'.$R_L.';">
								'. $txt['pmx_text_replies'] . $post['replies'] .'
							</div>
							<br style="clear:both;" />
							<div class="smalltext msg_bot_pad" style="float:'.$L_R.';">
								'. $txt['pmx_text_board'] .'<a href="' . $scripturl . '?board='. $post['id_board'] .'.0">'. $post['board_name'] .'</a>
							</div>
							<div class="smalltext msg_bot_pad" style="float:'.$R_L.';">
							'. $txt['pmx_text_views'] . $post['views'] .'
							</div>
							<hr style="clear:both;" />';

				if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
					echo '
							<div class="pmxhs_imglink" onmouseover="this.className = \'contentover\'" onmouseout="this.className =\'contentout\'" title="'. $txt['pmx_hs_read'] .'" onclick="return hs.htmlExpand(this,
									{ maincontentId: \'mbn_contid'. $post['message_id'] .'\', align: \'center\', wrapperClassName: \'highslide-wrapper-html\' })">';
				else
					echo '
							<div class="pmxhs_imglink">';

				if(!empty($this->cfg['config']['settings']['teaser']))
					echo PortaMx_Tease_posts($post['body'], $this->cfg['config']['settings']['teaser'], '', false, empty($this->cfg['config']['settings']['rescale']));
				else
					echo PortaMx_revoveLinks($post['body'], false, empty($this->cfg['config']['settings']['rescale']));

				// post has attach?
				$msgattach = '';
				if(isset($this->attaches[$post['message_id']]))
				{
					$msgattach = '
								<div  class="pmxhs_posting" style="text-align:'.$L_R.';">';
					echo $msgattach;

					foreach($this->attaches[$post['message_id']] as $att)
					{
						if($att['thumb'] != $att['image'])
						{
							$msgattach .= '
									<a href="'. $scripturl .'?action=dlattach;topic='. $post['id'] .'.0;attach='. $att['image'] .';image"  class="highslide" title="'. $txt['pmx_hs_expand'] .'" onclick="return hs.expand(this, {align: \'center\', captionEval: \'this.thumb.title\'})">
										<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['id'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />
									</a>';

							echo '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['id'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />';
						}
						else
						{
							$msgattach .= '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['id'] .'.0;attach='. $att['thumb'] .';image" alt="" title="'. $att['fname'] .'" />';
							echo '
									<img align="top" class="pmxhs_postattach" src="'. $scripturl .'?action=dlattach;topic='. $post['id'] .'.0;attach='. $att['thumb'] .';image" alt="'. $att['fname'] .'" title="" />';
						}
					}

					$msgattach .= '
								</div>';
					echo '
								</div>';
				}

				echo '
							</div>';

				if(!empty($this->cfg['config']['settings']['equal']) && !empty($this->cfg['config']['settings']['split']))
					echo '
							</div>';

				echo '
							<a class="smalltext" href="'. $scripturl . '?topic=' . $post['id'] . '.0">'. $txt['pmx_text_readmore'] .'</a>';

				// highslide code
				if(empty($context['pmx']['settings']['disableHS']) && empty($this->cfg['config']['settings']['disableHS']))
				{
					echo '
							<div class="highslide-maincontent" id="mbn_contid'. $post['message_id'] .'">
								<div class="highslide-posthead">
									'. $post['icon'] .'<span class="normaltext cat_msg_title">'. $post['subject'] .'</span>
								</div>
								<div class="smalltext" style="float:'.$L_R.';">
									'. $txt['pmx_text_postby'] . preg_replace('~<[^>]*>~i', '', $post['poster']['link']) .', '. $post['time'] .'
								</div>
								<div class="smalltext" style="float:'.$R_L.';">
									'. $txt['pmx_text_replies'] . $post['replies'] .'
								</div>
								<br style="clear:both;" />
								<div class="smalltext msg_bot_pad" style="float:'.$L_R.';">
									'. $txt['pmx_text_board'] . $post['board_name'] .'
								</div>
								<div class="smalltext msg_bot_pad" style="float:'.$R_L.';">
								'. $txt['pmx_text_views'] . $post['views'] .'
								</div>
								<hr style="clear:both;" />';

					if(empty($this->cfg['config']['settings']['rescale']))
						echo '
								'. PortaMx_revoveLinks($post['body'], true, empty($this->cfg['config']['settings']['rescale'])) . $msgattach;
					elseif(isset($post['hsbody']))
						echo '
								'. PortaMx_revoveLinks($post['hsbody'], true, empty($this->cfg['config']['settings']['rescale'])) . $msgattach;
					echo '
							</div>';
				}

				if(!empty($this->cfg['config']['visuals']['postframe']))
				{
					if($this->cfg['config']['visuals']['postframe'] == 'roundframe' || $isCustFrame)
						echo '
							</div>
							<span class="'. $spanclass . ($isCustFrame ? $this->cfg['config']['visuals']['postframe'] .'_bot' : 'lowerframe') .'"><span></span></span>';
					else
						echo '
							</div>
							<span class="'. (!empty($this->cfg['config']['visuals']['postbody']) ? $this->cfg['config']['visuals']['postbody'] .' ' : '') .'botslice"><span></span></span>';
				}
				elseif(!empty($postbody))
					echo '
							</div>';

				echo '
							</div>';

				if($is_Split)
					next($this->posts);
			}

			if($is_Split && $half == 0 && count($this->posts) % 2 != 0)
				echo '
						</td>
						<td style="padding-'.$L_R.':'. ceil($context['pmx']['settings']['panelpad'] / 2) .'px; width:50%;" valign="top">';

			echo '
						</td>
					</tr>
				</table>';

			if(!empty($this->pageindex))
				echo '
				<div class="smalltext pmx_pgidx_bot">'. $txt['pages']. ': '. $this->pageindex . (!empty($modSettings['topbottomEnable']) ? $context['menu_separator'] . ' &nbsp;&nbsp;<a href="#top'. $this->cfg['uniID'] .'"><strong>' . $txt['go_up'] . '</strong></a>' : '') .'</div>';

			if(!empty($this->cfg['config']['settings']['rescale']))
				echo '
				<script language="JavaScript" type="text/javascript"><!-- // --><![CDATA[
					MsgImages'.$this->cfg['id'].'['. $jsImg .'] = window.setInterval("ResizeImages(\''.$this->cfg['id'].'\', '. $this->cfg['config']['settings']['rescale'] .')", 20);
				// ]]></script>';
		}
	}
}
?>